#include <crsparse.h>
using namespace crsparse;

void compress(ostream_base& os, istream_base& is)
{
	direct_pusher direct(os);
	sparse_encoder<direct_pusher> sparse;
	sparse.setnext(&direct);

	try {
		while (true) 
			sparse.push(is.getbyte());
	}
	catch (exception<stream_base>& e)
	{
		if (e.code == stream_base::eos && e.obj == &is)
			sparse.final();
		else CR_Prompt(_T("istream_base raised unknown exception"));
	}

}

void decompress(ostream_base& os, istream_base& is)
{
	direct_pusher direct(os);
	sparse_decoder<direct_pusher> sparse;
	sparse.setnext(&direct);

	try {
		while (true)
			sparse.push(is.getbyte());
	}
	catch (exception<stream_base>& e)
	{
		if (e.code == stream_base::eos && e.obj == &is)
			sparse.final();
		else CR_Prompt(_T("istream_base raised unknown exception"));
	}

}

int _tmain(int argc, _TCHAR* argv[])
{
#if 0
	const char testdoc[] = "0123456789/*aaaaaaaa0011111111111111";
	const char testdoc[] = "0123456789/*aa00011111111111111";
	const char testdoc[] = "0123456789/*aa00000000000000000000000011111111111111";
#else
	const char testdoc[] = "0123456789/*00aaaaaaabcdefaaaaaaaaaaaaaaaaa0000001111111111111100";
#endif 

	const size_t doclen = strlen(testdoc) + 1;

	byte encbuf[4096];
	byte decbuf[4096];
	size_t enclen = 0;
	size_t declen = 0;

	printf("sparse:flag=");
	printf("\"");
	for (int i=0; i<sparsebase::flag_rep; ++i)
		printf("%c", sparsebase::flag_ch);
	printf("\"(0x");
	for (int i=0; i<sparsebase::flag_rep; ++i)
		printf("%X", sparsebase::flag_ch);
	printf(")\n");

	printf(testdoc);
	printf("\n");

	{
		ostream_base os;
		os.bind(encbuf, 4096);
		istream_base is;
		is.bind((byte*)testdoc, doclen);
		compress(os, is);
		enclen = os.occupy();
	}

	encbuf[enclen] = NULL;
	printf((char*)encbuf);
	printf("\n");

	{
		ostream_base os;
		os.bind(decbuf, 4096);
		istream_base is;
		is.bind(encbuf, enclen);
		decompress(os, is);
		declen = os.occupy();
	}

	decbuf[declen] = NULL;
	printf((char*)decbuf);
	printf("\n");

	system("pause");
	return 0;
}

